layui.define('form', function (exports) {
    var $ = layui.$
        , setter = layui.setter
        , admin = layui.admin
        , form = layui.form
        , router = layui.router()
        , search = router.search;

    var loginState = false;// 标记当前是否正在登录,如果已经在登陆了，那就不需要再提交表单了。

    //提交
    form.render();
    form.on('submit(LAY-user-login-submit)', function (obj) {
        if (loginState) {
            return;
        }

        //请求登入接口
        admin.req({
            url: '/login',
            type: "post",
            data: obj.field,
            beforeSend: function () {
                loginState = true;
                layer.load(2, {time: 100 * 1000});
            },
            complete: function () {
                loginState = false;
                layer.closeAll('loading');
            },
            done: function (res) {
                layui.data(setter.tableName, {
                    key: setter.request.tokenName,
                    value: res.data.access_token
                });

                //登入成功的提示与跳转
                layer.msg('登入成功', {icon: 1, time: 1000}, function () {
                    loginState = false;
                    if(res.data.index) {
                        location.hash = search.redirect ? decodeURIComponent(search.redirect) : res.data.index;
                    } else{
                        location.hash = search.redirect ? decodeURIComponent(search.redirect) : '/bill/expressAdd';
                    }
                });
            }
        });

    });

    form.verify({
        username: function (value, item) {//value：表单的值、item：表单的DOM对象
            if (value.length > 20 || value.length < 6) {
                return '登录名只能是6-20位字符长度';
            }
            if (!new RegExp("^\\w+$").test(value)) {
                return '登录名只能由字母、数字、下划线组成';
            }
        },
        password: function (value, item) {
            if (value.length > 20 || value.length < 6) {
                return '密码只能是6-20位字符长度';
            }
        }
    });

    $("body").on("keydown", function (e) {
        var theEvent = window.event || e;
        var code = theEvent.keyCode || theEvent.which;
        if (code == 13) {
            $("#LAY-user-login")
                .find("button")
                .click();
        }
    });

    $("#bil-express-query-btn").off("click").on("click", function() {
        var waybillNo = $("#bil-express-waybillNo").val();
        if(waybillNo.length === 0) {
            return;
        }

        layer.open({
            type: 2,
            title: "运单号【" + waybillNo + "】运单物流信息",
            area: ['800px', '500px'],
            content: layui.setter.base + 'views/bil/logisticsList.html?waybillNo=' + waybillNo,
            cancel: function(index, layero){
                layer.close(index);
                return false;
            }
        });
    });

    //对外暴露的接口
    exports('login', {});
});